<?php
/**
 * Description
 * User: duanwenjie
 * Date: 2019/5/9
 * Time: 11:59 AM
 */

namespace app\index\service;
use app\common\ConfigBase;
use app\common\model\ToolModel;
use app\common\service\DownService;
use app\common\service\SkuService;
use think\Db;
use think\Exception;

class PurchaseplanService
{
    static public function getPurchaseplanList($param, $is_download = false)
    {
        try{
            $where = "where 1 = 1 ";
            $pageNumber = isset($param['page']) ? $param['page'] : 1;
            $pageData = isset($param['limit']) ? $param['limit'] : 20;
            $purchase_plan_sn = isset($param['purchase_plan_sn']) ? $param['purchase_plan_sn'] : '';  //采购计划单号
            $pr = isset($param['pr']) ? $param['pr'] : '';  //pr单号
            $pr_time = isset($param['pr_time']) ? $param['pr_time'] : '';  //pr时间
            $base_country_id = isset($param['base_country_id']) ? $param['base_country_id'] : '';  //国家ID
            $base_shop_id = isset($param['base_shop_id']) ? $param['base_shop_id'] : '';  //店铺ID
            $status = isset($param['status']) ? $param['status'] : '';  //状态
            $offset = ($pageNumber - 1) * $pageData;
            $limit = " LIMIT $offset,$pageData";

            if (!empty($purchase_plan_sn)) {
                $purchase_plan_sn = trim($purchase_plan_sn);
                $where .= " AND purchase_plan_sn = '{$purchase_plan_sn}'";
            }
            if (!empty($pr)) {
                $pr = trim($pr);
                $where .= " AND pr = '{$pr}'";
            }
            if (!empty($pr_time)) {
                $date = explode(' - ', $pr_time);
                if (count($date) == 2){
                    $where .= " AND pr_time >= '$date[0]'";
                    $where .= " AND pr_time <= '$date[1]'";
                }
            }
            if (!empty($base_country_id)) {
                $base_country_id = trim($base_country_id);
                $where .= " AND base_country_id = {$base_country_id}";
            }
            if (!empty($base_shop_id)) {
                $base_shop_id = trim($base_shop_id);
                $where .= " AND base_shop_id = {$base_shop_id}";
            }
            if (!empty($status)) {
                $where .= " AND status = {$status}";
            }

            $sqlCount = "SELECT COUNT(id) num FROM purchase_plan {$where}";
            $countArr = ToolModel::queryData($sqlCount);
            if (empty($countArr) || $countArr[0]['num'] == 0) {
                if ($is_download) exitJson(["code" => "500", "msg" => "无有效数据"]);
                return array('total' => 0, 'list' => array());
            }
            $fileds = 'id,purchase_plan_sn,shop_sale_plan_sn,base_country_name,base_shop_name,sku,sku_name,
                      need_quantity,quantity,arrive_time,batch,interval_day,pr,pr_time,pr_state,
                      case pr_state  when -1 then "计划撤销"  when 0 then "待采购" when 1 then "已生成采购单" end pr_state_name,
                      po,upload,operator,update_time,status,unusual_reason,
                      case status when 1 then "已确定" when -1 then "未确定" end status_name';

            $sql = "SELECT {$fileds} FROM purchase_plan {$where} ORDER BY id DESC {$limit}";
            if ($is_download) return "SELECT {$fileds} FROM purchase_plan {$where} ORDER BY id DESC ";

            $list = ToolModel::queryData($sql);
            foreach ($list as &$value){
                if ($value['arrive_time'] == "0000-00-00 00:00:00") $value['arrive_time'] = "";
                if ($value['pr_time'] == "0000-00-00 00:00:00") $value['pr_time'] = "";
                if ($value['po'] == "0") $value['po'] = "";
                if (!empty($value['po'])) $value['unusual_reason'] = "";
            }
            $data = array();
            $data['total'] = intval($countArr[0]['num']);
            $data['list'] = $list;

            return $data;
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 上传数据处理
     * @param $data
     * @param $param
     * @return array
     * @throws Exception
     * @author duanwenjie
     */
    static public function uploadHandle($data, $param)
    {
        try{
            $line = 1;
            $error = array();
            $shops = array();
            $skus = array();
            $data_ = array();
            foreach ($data as $itm){
                $line ++;
                if (empty(trim($itm[0]))) {
                    $error[] = '第' . $line . '行店铺销售计划单号为空';
                    continue;
                }
                if (empty(trim($itm[1]))) {
                    $error[] = '第' . $line . '行店铺为空';
                    continue;
                }
                if (empty(trim($itm[2]))) {
                    $error[] = '第' . $line . '行SKU为空';
                    continue;
                }
                if (empty(trim($itm[3]))) {
                    $error[] = '第' . $line . '行理论需求量为空';
                    continue;
                }
                if (empty(trim($itm[4]))) {
                    $error[] = '第' . $line . '行实际下单量为空';
                    continue;
                }
                if (empty(trim($itm[5]))) {
                    $error[] = '第' . $line . '行首批到货日期为空';
                    continue;
                }
                if (empty(trim($itm[6]))) {
                    $error[] = '第' . $line . '行批次为空';
                    continue;
                }
                if (empty(trim($itm[7]))) {
                    $error[] = '第' . $line . '行间隔时间为空';
                    continue;
                }

                $data_[] = $itm;
                $shops[] = trim($itm[1]);
                $skus[] = trim($itm[2]);
            }

            if (!empty($data_)) {
                $error1 = self::checkSkus($skus);
                $error2 = self::checkShop($shops);
                if (!empty($error1)) $error = array_merge($error,$error1);
                if (!empty($error2)) $error = array_merge($error,$error2);
            }else{
                $error[] = "无有效数据";
            }
            $exist_items = array();
            $data_insert = array();
            if(!empty($error)){
                return ["code" => "500", "msg" => join('<br/>',$error)];
            }else{
                if (!empty($data_)){
                    $shops = array_flip(ConfigBase::getShop()); // 店铺数据
                    $shop_names = array_column(array_values($data_),'1'); // 店铺名数组
                    $shop_names_infos = self::checkShop($shop_names,true); // 店铺名数组关信息
                    $skus = array_column(array_values($data_),'2'); // sku数组
                    $skus_info = self::checkSkus($skus,true); // SKU相关信息
                    $purchase_plan_sn = ToolModel::createSerialNumber('CG1','4'); // 生成采购计划单号 (同一批次的采购计划取一样)
                    // 插入数据到数据库 purchase_plan
                    foreach ($data_ as $value){
                        $tmb_str = json_encode($value);
                        if (in_array($tmb_str,$exist_items)) continue; // 重复的数据跳过
                        $exist_items[] = $tmb_str;
                        $data_insert[] = array(
                            "purchase_plan_sn" => $purchase_plan_sn,
                            "shop_sale_plan_sn" => trim($value[0]),
                            "base_shop_id" => isset($shops[trim($value[1])]) ? $shops[trim($value[1])] : 0,
                            "base_shop_name" => trim($value[1]),
                            "base_country_id" => isset($shop_names_infos[trim($value[1])]['base_country_id']) ? $shop_names_infos[trim($value[1])]['base_country_id'] : 0,
                            "base_country_name" => isset($shop_names_infos[trim($value[1])]['base_country_name']) ? $shop_names_infos[trim($value[1])]['base_country_name'] : '',
                            "sku" => trim($value[2]),
                            "sku_name" => in_array(trim($value[2]),array_keys($skus_info)) ? $skus_info[trim($value[2])]['name'] : '',
                            "need_quantity" => trim($value[3]),
                            "quantity" => trim($value[4]),
                            "arrive_time" => trim($value[5]),
                            "batch" => trim($value[6]),
                            "interval_day" => trim($value[7]),
                            "upload" => CN_NAME ? CN_NAME : 'admin',
                            "operator" => CN_NAME ? CN_NAME : 'admin'
                        );
                    }
                }
                ToolModel::dbInsertAll('purchase_plan',$data_insert); // 批量插入
                return ["code" => "1", "msg" => "成功"];
            }
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 校验SKU是否存在
     * @param array $skus
     * @return array
     * @author duanwenjie
     */
    static public function checkSkus($skus = array(),$is_need_skuinfos = false)
    {
        $res = SkuService::getSkuBySku($skus);
        if ($is_need_skuinfos) return $res;
        $exist_skus = array();
        if (!empty($res)) $exist_skus = array_keys($res);
        $error = array();
        foreach ($skus as $v){
            if (!in_array($v,$exist_skus)) $error[] = "SKU：({$v})在SKU基础资料中不存在";
        }

        return $error;
    }

    /**
     * 校验店铺是否存在
     * @param array $shops
     * @return array
     * @author duanwenjie
     */
    static public function checkShop($shops = array(), $is_need_shopinfos = false)
    {
        $res = Db::name('base_shop')->field('shop_name')->column('id,shop_name,base_country_id,base_country_name','shop_name');
        if ($is_need_shopinfos) return $res;
        $error = array();
        foreach ($shops as $v){
            if (!in_array($v,array_keys($res))) $error[] = "店铺：({$v})在店铺列表中不存在";
        }

        return $error;
    }

    /**
     * 导出数据
     * @param $param
     * @return array
     * @author duanwenjie
     */
    static public function export($param)
    {
        $sql = self::getPurchaseplanList($param,true);
        $title = array(
            'purchase_plan_sn' => '采购计划单号',
            'shop_sale_plan_sn' => '店铺销售计划单号',
            'base_country_name' => '国家',
            'base_shop_name' => '店铺名称',
            'sku' => 'SKU',
            'sku_name' => 'SKU中文名称',
            'need_quantity' => '理论需求数量',
            'quantity' => '实际下单数量',
            'arrive_time' => '首批到货日期',
            'batch' => '批次',
            'interval_day' => '间隔时间(天)',
            'pr' => 'PR单号',
            'pr_time' => 'PR时间',
            'pr_state_name' => 'PR状态',
            'po' => 'PO单号',
            'upload' => '上传人',
            'operator' => '修改人',
            'update_time' => '修改时间',
            'status_name' => '状态'
        );

        $res = DownService::getData($sql,$title,'',$param);

        return $res;
    }


    /**
     * 批量创建采购计划并同步到进销存
     * @param array $param
     * @return bool|int
     * @throws Exception
     * @author duanwenjie
     */
    static public function createPrPushNewErp($param = array())
    {
        try{
            $ids = $param['id'];
            $data = Db::name('purchase_plan')->field('id,purchase_plan_sn,sku,quantity,arrive_time')->where('id','in',$ids)->select();
            $param_data[1] = array( // 从1开始，和进销存数据保持一致
                "A" => "sku",
                "B" => "下单数量",
                "C" => "交期/取货日期",
                "D" => "网拍链接",
                "E" => "物流方式",
                "F" => "仓库",
                "G" => "仓别",
                "H" => "转运仓库",
                "I" => "运输方式",
                "J" => "运费",
                "K" => "备注",
                "L" => "需求时间"
            );

            if (!empty($data)){
                foreach ($data as $value){
                    $temp = array(
                        "A" => $value['sku'],
                        "B" => $value['quantity'],
                        "C" => $value['arrive_time'],
                        "D" => "",
                        "E" => "供应商包邮",
                        "F" => "国内仓",
                        "G" => 7,
                        "H" => "",
                        "I" => "",
                        "J" => 0,
                        "K" => "YUJISO采购单",
                        "L" => ""
                    );
                    $param_data[] = $temp;
                }
            }
            $url = config('apiNewErpUrl') . 'commonapi/yujiso/receiveYujisoData';
            $param_data['user_name'] = CN_NAME ? CN_NAME : 'admin'; // 切换为用户名，方便进销存查找对应的用户（两边系统用户名是一致的，user_id是不一致的）
            $response = curl($url, json_encode($param_data), array('Content-Type: application/json'));
            $json = json_decode($response, TRUE);
            $data_ = array();
            if (!$json || !isset($json['code']) || $json['code'] !== '000001') {
                trace('url=' . $url . ',param=' . json_encode($param).'response=' . $response, 'error');
            }else{
                $data_ = $json['data'];
            }
            $data_update = array();
            $sku_counts = array();
            if (!empty($data)){
                $exist_sku = array();
                foreach ($data as $value_){
                    if (in_array($value_['sku'],$exist_sku)){
                        $sku_counts[$value_['sku']] += 1;
                    }else{
                        $exist_sku[] = $value_['sku'];
                        $sku_counts[$value_['sku']] = 1;
                    }
                }
            }
            $temp_sku = array();
            if (!empty($data_)){
                $skus = array_keys($data_);
                foreach ($data as $k => $v){
                    $temp = array(
                        "id" => $v['id'],
                        "status" => 1 // 状态为已确定
                    );
                    if (in_array($v['sku'],$skus)){
                        if (isset($sku_counts[$v['sku']]) && $sku_counts[$v['sku']] > 1){
                            $temp_sku[$v['sku']][] = $v['sku'];
                            $temp['pr'] = (is_numeric($data_[$v['sku']])) ? ($data_[$v['sku']] - ($sku_counts[$v['sku']] - count($temp_sku[$v['sku']]))) : '';
                        }else{
                            $temp['pr'] = (is_numeric($data_[$v['sku']])) ? $data_[$v['sku']] : '';
                        }
                        $temp['pr_time'] = (is_numeric($data_[$v['sku']])) ? date('Y-m-d H:i:s') : '';
                    }
                    $data_update[] = $temp;
                }
            }

            $res_ = 0;
            if (!empty($data_update)){
                $res_ = ToolModel::dbInsertOrUpdate('purchase_plan',$data_update);
                /*调取进销存PR数据同步接口同步数据到YUJISO*/
                if ($res_) TasksService::syncNewErpPrToYujiso();
            }
            return $res_;
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }
}